import tkinter as tk
from tkinter import ttk


class TopicsSelect(tk.Toplevel):
    def __init__(self, parent, topics, last_seleced_topics, callback):
        self.callback = callback
        tk.Toplevel.__init__(self, parent)
        self.title("Select Published Topics")
        self.select_all_button = ttk.Button(
            self, text="Select All", command=self.SelectAll)
        self.select_all_button.grid(
            row=0, column=0, padx=5, pady=5, sticky="w")
        self.selected_topics = []
        self.canvas = tk.Canvas(self)
        self.canvas.config(width=600, height=200)
        self.canvas.grid(row=1, column=0, padx=5, pady=5)
        self.scrollbar = ttk.Scrollbar(self, orient="vertical")
        self.scrollbar.grid(row=1, column=2, sticky="ns")
        self.scrollbar.config(command=self.canvas.yview)
        self.canvas.config(yscrollcommand=self.scrollbar.set)
        self.canvas.bind('<Configure>', lambda x: self.OnCanvasConfigure(x))
        self.frame = ttk.Frame(self.canvas)
        self.canvas.create_window((0, 0), window=self.frame, anchor="w")
        for i, topic in enumerate(topics):
            var = tk.BooleanVar(value=False)
            if topic in last_seleced_topics:
                var.set(True)
            checkbox = ttk.Checkbutton(
                self.frame, text=topic, variable=var)
            checkbox.grid(row=i, column=0, sticky="w")
            self.selected_topics.append((topic, var))
        self.confirm_button = ttk.Button(
            self, text="confirm", command=self.ConfirmSelection)
        self.confirm_button.grid(row=2, column=0, columnspan=1, padx=5, pady=5)
        self.bind("<KeyPress>", lambda x: self.OnKeyPress(x))

    def SelectAll(self):
        for topic, var in self.selected_topics:
            var.set(True)

    def OnKeyPress(self, event):
        if event.keysym == "Return":
            self.ConfirmSelection()

    def ConfirmSelection(self):
        self.selected_topics = [option[0]
                                for option in self.selected_topics if option[1].get()]
        self.callback(self.selected_topics)
        self.destroy()

    def OnCanvasConfigure(self, event):
        self.canvas.configure(scrollregion=self.canvas.bbox("all"))
